package demo.drools;

import com.alibaba.fastjson.JSONObject;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.ReleaseId;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.StatelessKieSession;
import org.kie.internal.io.ResourceFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;

/**
 * @author lingyun.wang on @date 2021/11/23
 */
public class DroolsDemo {
    private static final String RULES_PATH = "rules/";
    private KieServices kService;
    private KieContainer kContainer;
    private KieSession kieSession;

    public DroolsDemo() {
        kService = KieServices.Factory.get();
        KieFileSystem kieFileSystem = kService.newKieFileSystem();
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        Resource[] ruleFiles = null;
        try {
            ruleFiles = resourcePatternResolver.getResources("classpath:" + RULES_PATH + "**/.");
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (Resource file : ruleFiles) {
            String path = RULES_PATH + file.getFilename();
            kieFileSystem.write(ResourceFactory.newClassPathResource(path, "UTF-8"));
        }
        KieBuilder builder = kService.newKieBuilder(kieFileSystem);
        builder.buildAll();
        ReleaseId releaseId = kService.newReleaseId("test1", "test1", "1");
        kContainer = kService.getKieClasspathContainer();
    }
    public boolean execute(Object param){
        StatelessKieSession kSession = kContainer.newStatelessKieSession("test1");
        kSession.execute(param);
        return true;
    }
}
